package cqu.zhaiyixin20215521.huarondao.slice.huarondaoPlay;

import java.util.Arrays;

public class HuaRonDao{
    public final int rowNum;
    public final int colNum;
    private final int[] pieces;
    public HuaRonDao(int rowNum, int colNum, int[] initial_pieces) {
        this.rowNum = rowNum;
        this.colNum = colNum;
        pieces = Arrays.copyOf(initial_pieces, rowNum * colNum);
    }

    public static final int UP = 1, DOWN = 2, LEFT = 3, RIGHT = 4;
    public boolean shiftPiece(int direction, int row, int col) { //滑动方块
        if(pieces[row * colNum + col] == pieces.length - 1) {
            return false;
        }
        switch (direction) {
            case UP:
                return shiftPieceUP(row, col);
            case DOWN:
                return shiftPieceDown(row, col);
            case LEFT:
                return shiftPieceLeft(row, col);
            case RIGHT:
                return shiftPieceRight(row, col);
        }
        return false;
    }

    private boolean shiftPieceUP(int row, int col) {
        if(pieces[row * colNum + col] == pieces.length - 1) {
            return true;
        }
        if(0 < row && shiftPieceUP(row - 1, col)) {
            pieces[(row - 1) * colNum + col] = pieces[row * colNum + col];
            pieces[row * colNum + col] = pieces.length - 1;
            return true;
        }
        return false;
    }

    private boolean shiftPieceDown(int row, int col) {
        if(pieces[row * colNum + col] == pieces.length - 1) {
            return true;
        }
        if(row + 1 < rowNum && shiftPieceDown(row + 1, col)) {
            pieces[(row + 1) * colNum + col] = pieces[row * colNum + col];
            pieces[row * colNum + col] = pieces.length - 1;
            return true;
        }
        return false;
    }

    private boolean shiftPieceLeft(int row, int col) {
        if(pieces[row * colNum + col] == pieces.length - 1) {
            return true;
        }
        if(0 < col && shiftPieceLeft(row, col - 1)) {
            pieces[row * colNum + col - 1] = pieces[row * colNum + col];
            pieces[row * colNum + col] = pieces.length - 1;
            return true;
        }
        return false;
    }

    private boolean shiftPieceRight(int row, int col) {
        if(pieces[row * colNum + col] == pieces.length - 1) {
            return true;
        }
        if(col + 1 < colNum && shiftPieceRight(row, col + 1)) {
            pieces[row * colNum + col + 1] = pieces[row * colNum + col];
            pieces[row * colNum + col] = pieces.length - 1;
            return true;
        }
        return false;
    }

    public boolean allPiecesInPlace() { //判断图案是否正确
        for(int i = 0; i < pieces.length; ++i) {
            if(pieces[i] != i) {
                return false;
            }
        }
        return true;
    }

    public int get(int row, int col) {
        return pieces[row * colNum + col];
    }
}
